var map;
var features;
var featureOverlay;

//基站图层
var baseStationObj=new Object();
baseStationObj.layer=null;
baseStationObj.interaction=null;
//激活器图层
var activatorObj=new Object();
activatorObj.layer=null;
activatorObj.interaction=null;

$(function() {
    //初始化地图
    initMap();
	//显示基站点
    showBaseStation();
});


function initMap(){
    if(currentSelectTiles.name){
        $("#mapName").html("当前地图："+currentSelectTiles.name);
    }else{
        $("#mapName").html("当前地图：");
    }

    //初始化地图
    map = new ol.Map({
        layers : [ new ol.layer.Tile({
            source : new ol.source.XYZ({
                //url :  '/zhsq/userfiles/20180830222423_1/4-6/{z}/{x}/{y}.png'
                url :  $("#contextPath").val()+currentSelectTiles.tilesPath+'/4-6/{z}/{x}/{y}.png'
            })
            // source: new ol.source.OSM()
        }) ],
        controls : ol.control.defaults({
            attributionOptions : /** @type {olx.control.AttributionOptions} */
                ({
                    collapsible : false
                })
        }),
        logo : false,// 取消logo
        target : 'map',
        view : new ol.View({
            projection : 'EPSG:4326',
            center : [ 33.74975, 0 ],
            extent : [ 0, -21.94, 67.4995, 21.94 ],
            // center: ol.proj.transform([15,15], 'EPSG:4326', 'EPSG:3857'),
            // extent:ol.proj.transform([10,10, 20,20], 'EPSG:4326', 'EPSG:3857'),
            zoom : 4,
            minZoom : 4,
            maxZoom : 6
        })
    });

    //鼠标显示经纬度
    var mousePositionControl=new ol.control.MousePosition({
        coordinateFormat:ol.coordinate.createStringXY(4),
        projection:"EPSG:4326",
        className:"custom-mouse-position",
        target:document.getElementById("mouse-position"),
        undefinedHTML:"&nbsp",

    });
    map.addControl(mousePositionControl);


    features = new ol.Collection();
    featureOverlay = new ol.layer.Vector({
        source : new ol.source.Vector({
            features : features
        }),
        style : new ol.style.Style({
            fill : new ol.style.Fill({
                color : 'rgba(255, 255, 255, 0.05)'
            }),
            stroke : new ol.style.Stroke({
                color : '#ffcc33',
                width : 2
            }),
            image : new ol.style.Circle({
                radius : 7,
                fill : new ol.style.Fill({
                    color : '#ffcc33'
                })
            })
        })
    });
    featureOverlay.setMap(map);

    //初始化选中事件
    initSelectClick();

}
//选择颜色
var selectStyle = new ol.style.Style({
    fill: new ol.style.Fill({ //矢量图层填充颜色，以及透明度
        color: 'rgba(0, 0, 255, 0.15)'
        //color: 'rgba(0, 0, 255, 0.4)'
    }),
    stroke: new ol.style.Stroke({ //边界样式
        color: '#01f6ff',
        width: 3
    }),
    text: new ol.style.Text({ //文本样式
        font: '18px Calibri,sans-serif',
        fill: new ol.style.Fill({
            color: '#000'
        }),
        stroke: new ol.style.Stroke({
            color: '#fff',
            width: 3
        }) ,
        offsetX:-5,
        offsetY:25
    })
    ,
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        src: $("#contextPath").val()+'/userfiles/points/select32.png'
    }))
});
//初始化选中事件
var selectClick=null;
function initSelectClick(){
    if(selectClick!=null){
        map.removeInteraction(selectClick);
    }
    //选择事件
    selectClick = new ol.interaction.Select({
        condition: ol.events.condition.click,
        style:selectStyle,

    });
    map.addInteraction(selectClick);
    //选择事件
    selectClick.on('select', function(evt) {
        var selected=evt.selected;
        //气泡
        if (selected !=null) {
            var coordinate = evt.coordinate;
            for (var s in selected){
                //console.info(c+" = "+feature[c])
                var select=selected[s];
                if(selected[s].get("type")!=1 && selected[s].get("type")!=2){
                    var content=getItemById(selected[s].get("id"),selected[s].get("type"));
                    if(content!=""){
                        $('#popup-content').html(content);
                        document.getElementById("popup").style.left="-50px";
                        overlay = new ol.Overlay(({
                            element: document.getElementById('popup'),
                            autoPan: true,
                            autoPanAnimation: {
                                duration: 250   //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度.
                            }
                        }));
                        overlay.setPosition(selected[s].getGeometry().getCoordinates());
                        map.addOverlay(overlay);
                        $('#popup-closer').on('click', function (event) {
                            if(overlay!=null){overlay.setPosition(undefined);}
                            $('#popup-closer').blur();
                            return false;
                        });// 点击关闭的按钮
                    }
                }
            }
        }
    });
}


//显示or隐藏基站点
function showOrHideBaseStation(checkbox) {
    if ( checkbox.checked == true){
        showBaseStation();
    }else{
        hideBaseStation();
    }
}
//显示基站点
var base_vector = null;
function showBaseStation() {
    var baseStyle = new ol.style.Style({
        text : new ol.style.Text({ // 文本样式
            font : '14px Calibri,sans-serif',
            fill : new ol.style.Fill({
                color : '#000'
            }),
            stroke : new ol.style.Stroke({
                color : '#fff',
                width : 3
            }),
            offsetX : -50,
            offsetY : 50
        }),
        image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
            ({
                opacity : 0.95,
                src : $("#contextPath").val()+'/userfiles/points/base24.png'
            }))
    });
    hideBaseStation();
    base_vector = new ol.layer.Vector({
        source : new ol.source.Vector({
            url : 'getBaseStationPointData',// 110100.json bei_jing.geo.json b1.json
            format : new ol.format.GeoJSON()
        }),
        style : function(feature, resolution) {
            return [ baseStyle ];
        }
    });
    addLayer(baseStationObj,base_vector);
}
//隐藏基站点
function hideBaseStation(){
    if(baseStationObj.layer){
        removeLayer(baseStationObj);
    }
}


//显示or隐藏激活器点
function showOrHideActivator(checkbox) {
    if ( checkbox.checked == true){
        showActivator();
    }else{
        hideActivator();
    }
}
//显示激活器点
var jihuoqi_vector = null;
function showActivator() {
    var activatorStyle = new ol.style.Style({
        text : new ol.style.Text({ // 文本样式
            font : '14px Calibri,sans-serif',
            fill : new ol.style.Fill({
                color : '#000'
            }),
            stroke : new ol.style.Stroke({
                color : '#fff',
                width : 3
            }),
            offsetX : -50,
            offsetY : 50
        }),
        image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
            ({
                opacity : 0.95,
                src : $("#contextPath").val()+'/userfiles/points/jihuoqi24.png'
            }))
    });
    hideActivator();
    jihuoqi_vector = new ol.layer.Vector({
        source : new ol.source.Vector({
            url : 'getActivatorPointData',// 110100.json bei_jing.geo.json b1.json
            format : new ol.format.GeoJSON()
        }),
        style : function(feature, resolution) {
            return [ activatorStyle ];
        }
    });
    addLayer(activatorObj,jihuoqi_vector);
}
//隐藏基站点
function hideActivator(){
    if(activatorObj.layer){
        removeLayer(activatorObj);
    }
}


//添加图层时，删除对应obj的layer ,style,点击事件
function addLayer(obj,layer){
    obj.layer=layer;
    map.addLayer(layer);
}
// 删除图层时，删除对应obj的layer ,style,点击事件
function removeLayer(obj){
    map.removeLayer(obj.layer);
    obj.layer=null;
    initSelectClick();
}
//清空人员查询信息
function doPersonClear(){
    $("#personRealName").val('');
    $("#personMobile").val('');
    $("#persondDwbqNo").val('');
}
//弹窗显示人员列表
function dialogShowPersonManage() {
        $("#electrocarTBody").html('');
        var obj={};
        obj["name"]= $("#personName").val();
        obj["mobile"]=$("#personMobile").val();
        obj["dwbqNo"]=$("#persondDwbqNo").val();
        var jsonInfo = JSON.stringify(obj);
        $.ajax({
            type: "POST",
            url: "dialogShowPersonManage",
            data : jsonInfo,
            dataType: "json",
            async:false,
            contentType: "application/json; charset=utf-8",
            success: function(data){
                var resObject=data.resObject;
                var list=resObject.list;
                var personTBodyHtml='';
                if(list){
                    for(var l in list ){
                        personTBodyHtml+='<tr  class="gradeA">'+
                            '<td>'+list[l].dataIndex+'</td>'+
                            '<td>'+list[l].name+'</td>'+
                            '<td>'+list[l].sexName+'</td>'+
                            '<td>'+list[l].address+'</td>'+
                            '<td>'+list[l].mobile+'</td>'+
                            '<td>'+list[l].dwbqNo+'</td>'+
                            '<td><a href="#" onclick="javascript:showPersonCurrentLocation('+list[l].id+');\" title="定位"><i class="fa fa-edit text-navy">定位</i></a>&nbsp;&nbsp;&nbsp;' +
                            '<a href="#" onclick="javascript:showPersonHistoryPath('+list[l].id+');\" title="轨迹"><i class="fa fa-edit text-navy">轨迹</i></a></td>'+
                            '</tr>';
                    }
                    var personBodyHtml='<table id="personTable" class="footable table table-stripped" data-page-size="15" data-filter=#filter><thead><tr>'+
                        '<th width="8%">序号</th>'+
                        '<th width="10%">姓名</th>'+
                        '<th width="10%">性别</th>'+
                        '<th width="20%">住址</th>'+
                        '<th width="20%">手机</th>'+
                        '<th width="15%">标签</th>'+
                        '<th>操作</th>'+
                        '</tr></thead>'+
                        '<tbody id="personTBody">'+personTBodyHtml+'</tbody>'+
                        '<tfoot><tr><td colspan="7"><ul class="pagination pull-right"></ul></td></tr></tfoot>'+
                        ' </table>';
                    $("#personBody").html(personBodyHtml);
                    $('.footable').footable();
                }
            },
            error: function(){
                alert("系统异常！");
            }
        });
}

//清空车辆查询信息
function doElectrocarClear(){
    $("#name").val('');
    $("#dwbqNo").val('');
}
//弹窗显示车辆列表
function dialogShowElectrocarManage() {
    $("#personBody").html('');
    var obj={};
    obj["name"]= $("#name").val();
    obj["dwbqNo"]=$("#dwbqNo").val();
    var jsonInfo = JSON.stringify(obj);
    $.ajax({
        type: "POST",
        url: "dialogShowGoodsManage",
        data : jsonInfo,
        dataType: "json",
        async:false,
        contentType: "application/json; charset=utf-8",
        success: function(data){
            var resObject=data.resObject;
            var list=resObject.list;
            var electrocarTBodyHtml='';
            if(list){
                for(var l in list ){
                    electrocarTBodyHtml+='<tr  class="gradeA">'+
                        '<td>'+list[l].dataIndex+'</td>'+
                    //'<td>'+list[l].typeName+'</td>'+
                    '<td>'+list[l].name+'</td>'+
                    '<td>'+(list[l].location==null?'':list[l].location)+'</td>'+
                    '<td>'+(list[l].description==null?'':list[l].description)+'</td>'+
                    '<td>'+list[l].dwbqNo+'</td>'+
                    '<td>'+
                    '<a href="#" onclick="javascript:showElectrocarHistoryPath('+list[l].id+');\" title="轨迹"><i class="fa fa-edit text-navy">轨迹</i></a></td>'+
                    '</tr>';
                }
                var electrocarBodyHtml='<table id="electrocarTable" class="footable table table-stripped" data-page-size="15" data-filter=#filter><thead><tr>'+
                                    '<th width="8%">序号</th>'+
                                    //'<th width="10%">类型</th>'+
                                    '<th width="10%">姓名</th>'+
                                    '<th width="15%">其他</th>'+
                                    '<th width="20%">描述</th>'+
                                    '<th width="10%">标签</th>'+
                                    '<th>操作</th>'+
                                    '</tr></thead>'+
                                    '<tbody id="electrocarTBody">'+electrocarTBodyHtml+'</tbody>'+
                                    '<tfoot><tr><td colspan="8"><ul class="pagination pull-right"></ul></td></tr></tfoot>'+
                                    ' </table>';
                $("#electrocarBody").html(electrocarBodyHtml);
                $('.footable').footable();
            }
        },
        error: function(){
            alert("系统异常！");
        }
    });
}

//显示人员定位
function showPersonCurrentLocation(personId) {
    $('#myModal1').modal('hide');
    lastX=0;
    lastY=0;
    removeAllMove();
    closeWebSocket();
    openWebSocket(1);
}
//显示人员历史轨迹
function showPersonHistoryPath(personId) {
    $('#myModal1').modal('hide');
    closeWebSocket();
    removeAllMove();
    showHistoryMove(personId,1);
}


var isStartPosition=true;
function startPosition() {
    closeWebSocket();
    lastX=0;
    lastY=0;
    removeAllMove();
    if(isStartPosition){
        openWebSocket(1);
        $("#startBtn").text("停止定位");
    }else{
        $("#startBtn").text("开始定位");
    }
    isStartPosition=!isStartPosition;
}

//显示助力车定位
function showElectrocarCurrentLocation(electrocarId) {
    $('#myModal2').modal('hide');
    removeAllMove();
    closeWebSocket();
    openWebSocket(1);
}
//显示助力车历史轨迹
function showElectrocarHistoryPath(electrocarId) {
    $('#myModal2').modal('hide');

    $("#startBtn").text("开始定位");
    isStartPosition=true;
    closeWebSocket();
    removeAllMove();
    showHistoryMove(electrocarId,1);
}

//根据ID和type查找元素
function getItemById(id,type){
    var obj=new Object();
    obj["id"]=id;
    obj["type"]=type;
    var jsonInfo=JSON.stringify(obj);
    console.info("jsonInfo"+jsonInfo);
    var contentHtml='';
    $.ajax({
        type: "POST",
        url: "getItemById",
        data:jsonInfo,
        dataType: "json",
        async:false,
        contentType: "application/json; charset=utf-8",
        success: function(data){
            console.info("data="+JSON.stringify(data))
            if(data.resObject!=null){
                contentHtml=getPopupContent(data.resObject,type)
            }
        },
        error: function(data){
            console.info("系统异常！");
        }
    });
    return contentHtml;
}

//生成popup内容
function getPopupContent(obj,type){
    var contentHtml='';
    if(type==3){
        contentHtml='名称:'+obj.name+"<br>"+
            'IP:'+obj.ip+"<br>"+
            '端口:'+obj.port+"<br>"+
            '类型:'+obj.typeName+"<br>";
    }else if(type==4){
        contentHtml='区域:'+obj.regionName+"<br>"+
            '编号:'+obj.sbbh+"<br>"+
            '组名:'+obj.groupName+"<br>"+
            '序号:'+obj.groupNo+"<br>"+
            '类型:'+obj.sblxName+"<br>";
    }
    return contentHtml;

}




//设置选中的地图层
function selectOnemapTile(selectMapTilesId){
    //alert("selectMapTilesId="+selectMapTilesId);
    $.ajax({
        type: "POST",
        url: "setSelectMapTiles?id="+selectMapTilesId,
        contentType: "application/json; charset=utf-8",
        success: function(msg){
            window.location.reload();
        },
        error: function(){
            alert("系统异常！");
        }
    });
}

var isFull=true;
function OpenFullScreen() {
    //window.location=$("#contextPath").val() +"/rfid/maplocation/mapLocationManage";
    if(isFull){
        $("#fullScreenBtn").text("退出全屏");
        try{
            fullScreen();
        }catch (e)
        {
        }
    }else{
        $("#fullScreenBtn").text("全屏显示");
        try{
            exitFullScreen();
        }catch (e)
        {

        }
    }
    isFull=!isFull;
}


function startShow(){
    setInterval(function(){
        showRegionPersonCount();
    },5000);//默认3秒钟刷新一次
    $('#myModal3').modal('show');
}

function stopShow(){
    clearInterval(showRegionPersonCount);//
    $('#myModal3').modal('hide');
}



//显示区域人数统计
function showRegionPersonCount() {
    $("#regionPersonCountBody").html('');
    var obj={};
    var jsonInfo = JSON.stringify(obj);
    $.ajax({
        type: "POST",
        url: "getRegionPersonCount",
        //data : jsonInfo,
        //dataType: "json",
        async:false,
        contentType: "application/json; charset=utf-8",
        success: function(data){
            var list=data.resObject;
            var regionPersonTBodyHtml='';
            if(list){
                var i=1;
                for(var l in list ){
                    regionPersonTBodyHtml+='<tr  class="gradeA">'+
                        '<td>'+i+'</td>'+
                        '<td>'+l+'</td>'+
                        '<td>'+list[l].length+'</td>'+
                        // '<td>'+
                        // '<a href="#" onclick="javascript:showElectrocarHistoryPath('+list[l].id+');\" title="轨迹"><i class="fa fa-edit text-navy">轨迹</i></a></td>'+
                        '</tr>';
                    i++;
                }
                var regionPersonCountBodyHtml='<table id="regionPersonTable" class="footable table table-stripped" data-page-size="15" data-filter=#filter><thead><tr>'+
                    '<th width="5%">序号</th>'+
                    '<th width="15%">区域名称</th>'+
                    '<th width="10%">数量</th>'+
                    // '<th>操作</th>'+
                    '</tr></thead>'+
                    '<tbody id="regionPersonTBody">'+regionPersonTBodyHtml+'</tbody>'+
                    '<tfoot><tr><td colspan="8"><ul class="pagination pull-right"></ul></td></tr></tfoot>'+
                    ' </table>';
                $("#regionPersonCountBody").html(regionPersonCountBodyHtml);
                // $('.footable').footable();


            }


        },
        error: function(msg){
            //alert("系统异常！");
        }
    });




}

